import playMode from '@/config/playMode'
import { shuffle } from '@/utils'

const type = {
  SET_PLAYLIST: 'SET_PLAYLIST',
  SET_PALYMODE: 'SET_PALYMODE',
  SET_CURRENT_INDEX: 'SET_CURRENT_INDEX',
  SET_PALYING_STATE: 'SET_PALYING_STATE',
  SET_FULL_SCREEN: 'SET_FULL_SCREEN',
  SET_SEQUENCE_LIST: 'SET_SEQUENCE_LIST',
  CLEAR_PLAYLIST: 'CLEAR_PLAYLIST'
}
const state = {
  playList: [],
  sequenceList: [],
  palyMode: playMode.sequence,
  currentIndex: 0,
  playing: false,
  fullScreen: true
}
const actions = {
  play({commit, state}, {list, index}) {
    let playList = list
    if (state.palyMode === playMode.random) {
      playList = shuffle(list)
    }

    if (!state.playList.length) {
      commit(type.SET_FULL_SCREEN, true)
    }
    commit(type.SET_SEQUENCE_LIST, list)
    commit(type.SET_PLAYLIST, playList)
    commit(type.SET_CURRENT_INDEX, index)
    commit(type.SET_PALYING_STATE, true)
  },
  deleteOne({commit, state}, {id, index}) {
    let playList = state.playList.slice()
    let sequenceList = state.sequenceList.slice()
    let currentIndex = state.currentIndex

    let sIndex = sequenceList.findIndex(item => item.id === id)

    playList.splice(index, 1)
    sequenceList.splice(sIndex, 1)

    if (currentIndex > index || currentIndex === playList.length) {
      currentIndex--
    }

    commit('SET_PLAYLIST', playList)
    commit('SET_SEQUENCE_LIST', sequenceList)
    commit('SET_CURRENT_INDEX', currentIndex)
    commit('SET_PALYING_STATE', !(playList.length === 0))
  }
}
const mutations = {
  [type.SET_PLAYLIST](state, playList) {
    state.playList = playList
  },
  [type.SET_PALYMODE](state, palyMode) {
    state.palyMode = palyMode
  },
  [type.SET_CURRENT_INDEX](state, index) {
    state.currentIndex = index
  },
  [type.SET_PALYING_STATE](state, playing) {
    state.playing = playing
  },
  [type.SET_FULL_SCREEN](state, isFull) {
    state.fullScreen = isFull
  },
  [type.SET_SEQUENCE_LIST](state, sequenceList) {
    state.sequenceList = sequenceList
  },
  [type.CLEAR_PLAYLIST](state) {
    state.playList = []
    state.playing = false
    state.sequenceList = []
    state.currentIndex = 0
  }
}
const getters = {
  mode(state) {
    return state.palyMode
  },
  playing(state) {
    return state.playing
  },
  fullScreen(state) {
    return state.fullScreen
  },
  currentSong(state) {
    return state.playList[state.currentIndex]
  },
  playList(state) {
    return state.playList
  },
  currentIndex(state) {
    return state.currentIndex
  },
  sequenceList(state) {
    return state.sequenceList
  }
}

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters
}